import json
import xml.etree.ElementTree as ET
from xml.dom import minidom
import re


def fix_json_quotes(json_str):
    """修复JSON字符串中未正确转义的引号"""
    # 处理XML属性中的双引号未转义问题
    # 在"</前面添加转义符（处理XML结束标签）
    fixed = re.sub(r'(?<!\\)"(?=</)', r'\"', json_str)
    # 处理version="1.0"中的引号
    fixed = re.sub(r'version=(?<!\\)"', r'version=\"', fixed)
    # 处理encoding="UTF-8"中的引号
    fixed = re.sub(r'encoding=(?<!\\)"', r'encoding=\"', fixed)
    return fixed


def extract_and_format_xml_from_json(json_str):
    """从JSON字符串中提取XML内容并进行格式化"""
    try:
        # 1. 修复JSON中的引号转义问题
        fixed_json = fix_json_quotes(json_str)

        # 2. 解析JSON字符串
        json_data = json.loads(fixed_json)

        # 3. 提取xmlStr字段内容
        if 'xmlStr' not in json_data:
            print("错误：JSON中未找到xmlStr字段")
            return None

        xml_content = json_data['xmlStr']
        print("提取到的原始XML内容：")
        print(xml_content)
        print("\n" + "-" * 60 + "\n")

        # 4. 修复XML格式问题
        xml_content = xml_content.replace('version="1.0"encoding', 'version="1.0" encoding')
        xml_content = xml_content.replace('"encoding', '" encoding')

        # 移除非法控制字符
        xml_content = re.sub(r'[^\x09\x0A\x0D\x20-\uD7FF\uE000-\uFFFD]', '', xml_content)

        # 5. 解析XML
        root = ET.fromstring(xml_content)

        # 6. 格式化XML
        rough_string = ET.tostring(root, 'utf-8')
        reparsed = minidom.parseString(rough_string)
        formatted_xml = reparsed.toprettyxml(indent="  ")

        # 7. 去除空行
        formatted_xml = '\n'.join([line for line in formatted_xml.split('\n') if line.strip()])

        return formatted_xml

    except json.JSONDecodeError as e:
        print(f"JSON解析错误: {str(e)}")
        print(f"错误位置: 行 {e.lineno}, 列 {e.colno}")
        print("修复后的JSON尝试:")
        print(fix_json_quotes(json_str))
        return None
    except ET.ParseError as e:
        print(f"XML解析错误: {str(e)}")
        line, col = e.position
        start = max(0, col - 30)
        end = min(len(xml_content), col + 30)
        print(f"错误位置附近: ...{xml_content[start:end]}...")
        return None
    except Exception as e:
        print(f"处理过程中发生错误: {str(e)}")
        return None


# 主程序
if __name__ == "__main__":
    # 原始JSON字符串（包含未正确转义的引号）
    json_input = '''{"accessToken":"11","xmlStr":"<?xml version="1.0"encoding="UTF-8"?><APPROVEDATAINFO><SBLSH_SHORT>5203301152FXWZ20250820496087</SBLSH_SHORT><SXBM>11520330009536573P400011910200701-01</SXBM><XZQHDM>520330</XZQHDM><EXPRESSTYPE>3</EXPRESSTYPE><YWLY/><BZSLBLRXM/><BZCLQD/><BZSJ/><SENDTODOMESSAGE/><EXCHANGENO/></APPROVEDATAINFO>"}'''

    # 处理并获取格式化结果
    result = extract_and_format_xml_from_json(json_input)

    # 输出结果
    if result:
        print("格式化后的XML内容：")
        print(result)
